package com.kili.file.service.impl;


import com.aliyun.oss.OSS;
import com.kili.file.config.systemparam.FileUploadOssParamConfig;
import com.kili.file.controller.request.FileUploadRequest;
import com.kili.file.exception.FileUploadException;
import com.kili.file.modal.File;
import com.kili.file.service.FileHandleService;
import com.kili.file.service.FileUploadService;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;


/**
 * FileUploadWithOssCloudStorage
 *
 * @author Gordon
 * @version 2019/3/28
 */
@Slf4j
@Setter
public class FileUploadWithOssCloudStorage implements FileUploadService {

    private FileUploadOssParamConfig paramConfig;

    private OSS ossClient;

    @Override
    public String uploadHandler(FileUploadRequest request) {
        String bucketName = paramConfig.getBucketName();
        return fileUploadByOSSCloud(ossClient, request, bucketName);
    }

    private String fileUploadByOSSCloud(OSS ossClient, FileUploadRequest request, String bucketName) {
        MultipartFile multipartFile = request.getFile();
        String fileName = multipartFile.getOriginalFilename();
        String url = request.getUrl();

        try {
            // Upload an object to bucket   org1:storage space    org2:file name
            ossClient.putObject(bucketName, url, new ByteArrayInputStream(multipartFile.getBytes()));
            // Determine whether an object residents in bucket
            if (!ossClient.doesObjectExist(bucketName, url)) {
                log.warn("File upload cloud but not exist - fileName : {}", fileName);
                throw new FileUploadException("upload error");
            }
        } catch (Exception ex) {
            log.error("FileUploadByOSSCloud error - fileName : {} request : {}", fileName, request, ex);
            throw new FileUploadException("upload error");
        }

        log.info("Oss cloud upload successful - url : {}", url);
        return url;
    }
}
